package com.guoqi.myserverdemo

import android.app.Service
import android.content.Intent
import android.os.IBinder
import android.util.Log
import com.guoqi.myclientdemo.Good
import com.guoqi.myclientdemo.ShoppingManager

class ShoppingService : Service() {

    val TAG = this.javaClass.simpleName

    private var goodList = ArrayList<Good>()

    private val shoppingManager = object : ShoppingManager.Stub() {
        override fun addGood(good: Good?) {
            synchronized(this) {
                if (goodList == null) {
                    goodList = ArrayList<Good>()
                }
                if (good == null) {
                    Log.e(TAG, "addGood()为空")
                } else {
                    goodList.add(good)
                    Log.e(TAG, "addGood() = " + good.toString())
                }
            }
        }

        override fun getGoods(): ArrayList<Good> {
            synchronized(this) {
                return if (goodList != null) {
                    goodList
                } else ArrayList<Good>()
            }
        }

        override fun delGood(good: Good?) {
            synchronized(this) {
                if (goodList == null) {
                    goodList = ArrayList<Good>()
                    Log.e(TAG, "当前goodList为空")
                } else {
                    if (good == null) {
                        Log.e(TAG, "delGood()为空")
                    } else {
                        goodList.removeAt(goodList.size - 1)
                        Log.e(TAG, "delGood() = " + good.toString())
                    }
                }

            }
        }

    }


    override fun onCreate() {
        super.onCreate()
        Log.e(TAG, "shoppingService已启动")
    }

    override fun onBind(intent: Intent?): IBinder? {
        Log.e(TAG, String.format("执行onBind() ,intent = %s", intent.toString()))
        return shoppingManager
    }
}